public class Solution3 {
    int[] dx = {1, -1, 0, 0};
    int[] dy = {0, 0, 1, -1};
    int ret;
    int m;
    int n;
    int[][] memo;
    // 解法一：递归
    public int longestIncreasingPath(int[][] matrix) {
        m = matrix.length;
        n = matrix[0].length;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                ret = Math.max(dfs(matrix, i, j), ret);
            }
        }
        return ret;
    }

    public int dfs(int[][] matrix, int i, int j) {
        int max = 1;
        for(int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && matrix[i][j] < matrix[x][y]) {
                max = Math.max(max, dfs(matrix, x, y) + 1);
            }
        }
        return max;
    }
    // 解法二：记忆化搜索
    public int longestIncreasingPath1(int[][] matrix) {
        m = matrix.length;
        n = matrix[0].length;
        memo = new int[m][n];

        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                ret = Math.max(dfs1(matrix, i, j,memo), ret);
            }
        }
        return ret;
    }

    public int dfs1(int[][] matrix, int i, int j, int[][] memo) {
        if(memo[i][j] != 0) {
            return memo[i][j];
        }
        int max = 1;
        for(int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && matrix[i][j] < matrix[x][y]) {
                max = Math.max(max, dfs1(matrix, x, y, memo) + 1);
            }
        }
        memo[i][j] = max;
        return max;
    }
}
